package com.ts.proj.json;


import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.ProjectEntity;
import com.ts.proj.entity.excelEntity.ProjectEntityExcel;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.service.ProjectService;
import com.ts.common.constant.ConsoleConstant;
import com.ts.util.PageData;
import com.ts.util.StringsUtil;
import com.ts.util.DateUtil;
import com.ts.util.EasyPoiUtil;
import com.ts.util.EntityAttributeUtil;
import com.ts.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;



import javax.servlet.http.HttpSession;

import com.ts.util.JsonUtils;

//说明 字符串：project，作为替换字符串 LOWERproject

@RestController
public class ProjectJson extends BaseController{

    @Autowired
    private ProjectService projectService;

    /**
     * 显示list
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/project-list/{page}/{size}")
    public Map<String,Object> projectList(@PathVariable("page") Integer page, @PathVariable("size") Integer size){

        HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");

        //用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }

        pageData.put("belongTo", user.getBelongTo());

        if(null!=pageData.get("pro_name_like")&&!"".equals(pageData.getString("pro_name_like"))){
            pageData.put("pro_name_like", pageData.getString("pro_name_like"));
        }
        if(null!=pageData.get("pro_company_like")&&!"".equals(pageData.getString("pro_company_like"))){
            pageData.put("pro_company_like", pageData.getString("pro_company_like"));
        }
        if(null!=pageData.get("pro_state")&&!"".equals(pageData.getString("pro_state"))){
            pageData.put("pro_state", pageData.getString("pro_state"));
        }
        if(null!=pageData.get("pro_category")&&!"".equals(pageData.getString("pro_category"))){
            pageData.put("pro_category", pageData.getString("pro_category"));
        }


        long count = projectService.count(pageData);
        List<ProjectEntity> projects = projectService.findAll(pageData,page-1,size);
        pageData.put("total",count);
        pageData.put("rows", projects);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/project-ins-upd-del/{id}")
    public Object logCreateUpdate(@PathVariable("id") String id){

        ProjectEntity project = projectService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();
        List<String> strings = EntityAttributeUtil.entityAttribute(ProjectEntity.class);
        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = ProjectEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().contains(StringsUtil.upperCase(attr))&&!method.getName().contains("get")){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(project, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(project, pageData.getString(attr));
                            }
                        }
                        if(method.getName().equals("setUserId")){
                            project.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            project.setBelongTo(systemUserEntity.getBelongTo());
                        }
                        if(method.getName().equals("setPowerLevel")){
                            project.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        projectService.save(project);
        return null;
    }

    @RequestMapping("/project-check/{proName}/{id}")
    public String projectCheck(@PathVariable("proName") String proName,@PathVariable("id") Integer id) {

        /**
         * id==-1,这个时候需要check
         * id!=-1,这个时候不需要check
         */
        if(id != -1){
            return "success";
        }
        ProjectEntity byId = projectService.findById(id);
        //如果不为空，编辑
        List<ProjectEntity> byProName = projectService.findByProName(proName);
        List<ProjectEntity> projectEntityList = new ArrayList<>();
        for(ProjectEntity p : byProName){
            if("N".equals(p.getDeleteFlag())){
                projectEntityList.add(p);
            }
        }
        if (projectEntityList.size() == 0) {
            return "success";
        }
        return "error";
    }

    @RequestMapping("/proState-check/{id}")
    public Map<String , String> check(@PathVariable("id") String id){
        ProjectEntity byId = projectService.findById(Integer.valueOf(id));
        String msg = "";
        if(byId != null){
            if(byId.getProState() == 1){
                byId.setProState(2);
                msg = "审核通过！目前项目为立项状态！";
            }else if(byId.getProState() == 2){
                byId.setProState(3);
                msg = "审核通过！目前项目为决策状态！";
            }else {
                msg = "此项目已为决策状态！";
            }
        }
        PageData pageData = new PageData();
        projectService.save(byId);
        pageData.put("msg", msg);
        return pageData;
    }

    @RequestMapping("/project-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<ProjectEntity> entitys = projectService.findAll(param);
        List<ProjectEntityExcel> excelEntities = new ArrayList<>();
        for(ProjectEntity tempEntity :entitys){
            ProjectEntityExcel excel = new CopyObjectEntity2EntityExcel<ProjectEntityExcel, ProjectEntity>().copy(ProjectEntityExcel.class, ProjectEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","", ProjectEntityExcel.class, DateUtil.getID()+".xls",response);
    }
}